<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card" :body-style="{ padding: '0px' }">
          <div class="profile-header">
            <div class="header-backdrop"></div>
            <div class="header-content">
              <el-avatar 
                :size="100" 
                :src="userInfo.sysUser.avatar" 
                class="profile-avatar"
              />
              <h2 class="profile-name">{{ userInfo.sysUser.nickname }}</h2>
            </div>
          </div>
          <div class="profile-info">
            <ul class="profile-list">
              <li>
                <div class="info-label">
                  <el-icon><User /></el-icon>
                  <span>用户名称</span>
                </div>
                <div class="info-content">{{ userInfo.sysUser.username }}</div>
              </li>
              <li>
                <div class="info-label">
                  <el-icon><Iphone /></el-icon>
                  <span>手机号码</span>
                </div>
                <div class="info-content">{{ userInfo.sysUser.mobile || '未设置' }}</div>
              </li>
              <li>
                <div class="info-label">
                  <el-icon><Message /></el-icon>
                  <span>用户邮箱</span>
                </div>
                <div class="info-content">{{ userInfo.sysUser.email || '未设置' }}</div>
              </li>
              <li>
                <div class="info-label">
                  <el-icon><UserFilled /></el-icon>
                  <span>所属角色</span>
                </div>
                <div class="info-content">{{ userInfo.roles.join(',') || '未设置' }}</div>
              </li>
              <li>
                <div class="info-label">
                  <el-icon><Calendar /></el-icon>
                  <span>创建日期</span>
                </div>
                <div class="info-content">{{ userInfo.sysUser.createTime }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧标签页 -->
      <el-col :span="16">
        <el-card class="tab-card">
          <el-tabs v-model="activeTab" class="profile-tabs">
            <!-- 基本资料 -->
            <el-tab-pane label="基本资料" name="basic">
              <el-form
                ref="userFormRef"
                :model="userForm"
                :rules="userRules"
                label-width="120px"
                class="profile-form"
              >
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="用户昵称" prop="nickname">
                      <el-input 
                        v-model="userForm.nickname" 
                        maxlength="30"
                        placeholder="请输入用户昵称"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号码" prop="mobile">
                      <el-input 
                        v-model="userForm.mobile" 
                        maxlength="11"
                        placeholder="请输入手机号码"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                      <el-input 
                        v-model="userForm.email" 
                        maxlength="50"
                        placeholder="请输入邮箱地址"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="微信号" prop="wechat">
                      <el-input 
                        v-model="userForm.wechat" 
                        maxlength="50"
                        placeholder="请输入微信号"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="性别" class="gender-form-item">
                      <el-radio-group v-model="userForm.sex">
                        <el-radio :value="1">男</el-radio>
                        <el-radio :value="2">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="职业类型" prop="professionType">
                      <el-select v-model="userForm.professionType" placeholder="请选择职业类型" clearable style="width: 100%;">
                        <el-option 
                          v-for="item in professionTypeOptions" 
                          :key="item.value" 
                          :label="item.label" 
                          :value="item.value" 
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="使用平台目标" prop="platformTarget" class="textarea-form-item">
                  <el-input 
                    v-model="userForm.platformTarget" 
                    type="textarea"
                    :rows="4"
                    maxlength="200"
                    show-word-limit
                    placeholder="请输入使用平台目标，描述您希望通过平台实现的目标..."
                  />
                </el-form-item>

                <el-form-item label="行业标签" prop="industryTagIds" class="tags-form-item">
                  <IndustryTagSelector v-model="userForm.industryTagIds" />
                </el-form-item>

                <el-form-item class="submit-form-item">
                  <el-button 
                    v-permission="['sys:user:update']"
                    type="primary" 
                    size="large"
                    @click="submitUserForm"
                    :loading="submitLoading"
                  >
                    <el-icon><Check /></el-icon>
                    保存更改
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 社交平台 -->
            <el-tab-pane label="社交平台" name="social">
              <div class="social-platform-section">
                <div class="section-header">
                  <h3>社交平台信息</h3>
                  <el-button type="primary" icon="Plus" @click="addSocialPlatform" >
                    添加平台
                  </el-button>
                </div>

                <div v-if="userForm.socialMediaList.length === 0" class="empty-state">
                  <el-empty description="暂无社交平台信息">
                    <el-button type="primary" @click="addSocialPlatform">立即添加</el-button>
                  </el-empty>
                </div>

                <div v-else class="platform-list">
                  <el-card 
                    v-for="(platform, index) in userForm.socialMediaList" 
                    :key="index"
                    class="platform-card"
                    shadow="hover"
                  >
                    <template #header>
                      <div class="platform-header">
                        <div class="platform-title">
                          <el-tag 
                            :type="getPlatformTagType(platform.platformType)"
                            size="large"
                          >
                            {{ getPlatformName(platform.platformType) }}
                          </el-tag>
                          <el-tag 
                            :type="platform.verificationType === 1 ? 'success' : 'info'"
                            size="small"
                            style="margin-left: 8px;"
                          >
                            {{ platform.verificationType === 1 ? '蓝V' : '个人' }}
                          </el-tag>
                        </div>
                        <div class="platform-actions">
                          <el-button 
                            type="primary" 
                            icon="Check" 
                            size="small"
                            @click="saveSocialPlatform(platform, index)"
                          >
                            保存
                          </el-button>
                          <el-button 
                            type="danger" 
                            icon="Delete" 
                            size="small"
                            @click="removeSocialPlatform(index)" 
                          >
                            删除
                          </el-button>
                        </div>
                      </div>
                    </template>

                    <el-form :model="platform" label-width="100px">
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <el-form-item label="平台类型">
                            <el-select v-model="platform.platformType" placeholder="请选择平台类型">
                              <el-option 
                                v-for="item in platformTypeOptions" 
                                :key="item.value" 
                                :label="item.label" 
                                :value="item.value" 
                              />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="账号类型">
                            <el-radio-group v-model="platform.verificationType">
                              <el-radio :value="0">个人</el-radio>
                              <el-radio :value="1">蓝V</el-radio>
                            </el-radio-group>
                          </el-form-item>
                        </el-col>
                      </el-row>

                      <el-form-item label="主页链接">
                        <el-input 
                          v-model="platform.homeUrl" 
                          placeholder="请输入主页链接地址"
                        />
                      </el-form-item>

                      <el-form-item label="粉丝数">
                        <el-input-number 
                          v-model="platform.fansCount" 
                          :min="0"
                          :max="99999999"
                          placeholder="请输入粉丝数"
                          style="width: 100%;"
                        />
                      </el-form-item>
                    </el-form>
                  </el-card>
                </div>

                <div class="form-actions">
                  <el-button 
                    type="success" 
                    icon="Check"
                    @click="batchSaveSocialPlatforms"
                    :loading="submitLoading"
                  >
                    批量保存
                  </el-button>
                  <el-button 
                    v-permission="['sys:user:update']"
                    type="primary" 
                    @click="submitUserForm"
                    :loading="submitLoading"
                  >
                    <el-icon><Check /></el-icon>
                    保存更改
                  </el-button>
                </div>
              </div>
            </el-tab-pane>

            <!-- 修改密码 -->
            <el-tab-pane label="修改密码" name="password">
              <el-form
                ref="pwdFormRef"
                :model="pwdForm"
                :rules="pwdRules"
                label-width="100px"
                class="profile-form"
              >
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input
                    v-model="pwdForm.oldPassword"
                    type="password"
                    placeholder="请输入旧密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="pwdForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="pwdForm.confirmPassword"
                    type="password"
                    placeholder="请确认新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button 
                    v-permission="['sys:user:update']"
                    type="primary" 
                    @click="submitPwdForm"
                    :loading="pwdLoading"
                  >
                    <el-icon><Key /></el-icon>
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Key, User, Phone, Message, Plus, Delete } from '@element-plus/icons-vue'
import { getUserProfileApi, updateUserProfileApi, updateUserPwdApi, getUserSocialMediaApi, createUserSocialMediaApi, updateUserSocialMediaApi, deleteUserSocialMediaApi, batchSaveUserSocialMediaApi, type SocialMediaItem } from '@/api/system/user'
import { getDictDataByDictTypeApi } from '@/api/system/dict'
import IndustryTagSelector from '@/components/IndustryTagSelector/index.vue'

const activeTab = ref('basic')
const userFormRef = ref()
const pwdFormRef = ref()

// 用户信息
const userInfo = ref<any>({
  sysUser: {},
  roles: []
})

// 数据字典选项
const professionTypeOptions = ref<any[]>([])
const platformTypeOptions = ref<any[]>([])

// 表单数据
const userForm = reactive({
  id: undefined,
  nickname: '',
  mobile: '',
  email: '',
  wechat: '',
  sex: 1,
  professionType: '',
  platformTarget: '',
  industryTagIds: [] as number[],
  socialMediaList: [] as any[]
})

const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单校验规则
const userRules = reactive<any>({
  nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  email: [
    { required: false, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  wechat: [
    { pattern: /^[a-zA-Z\d_-]{6,20}$/, message: '微信号格式不正确', trigger: 'blur' }
  ]
})

const pwdRules = reactive<any>({
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== pwdForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 添加loading状态
const submitLoading = ref(false)
const pwdLoading = ref(false)

// 获取数据字典
const getDictData = async () => {
  try {
    console.log('开始获取数据字典...')
    const { data } = await getDictDataByDictTypeApi(['profession_type', 'platform_type'])
    console.log('数据字典API返回数据:', data)
    
    // 检查返回数据结构
    if (data) {
      console.log('profession_type数据:', data.profession_type)
      console.log('platform_type数据:', data.platform_type)
      
      professionTypeOptions.value = data.profession_type?.list || []
      platformTypeOptions.value = data.platform_type?.list || []
      
      console.log('设置后的professionTypeOptions:', professionTypeOptions.value)
      console.log('设置后的platformTypeOptions:', platformTypeOptions.value)
    } else {
      console.warn('数据字典API返回数据为空')
      // 设置默认数据
      professionTypeOptions.value = [
        { value: '1', label: '自媒体运营者' },
        { value: '2', label: '公司运营' },
        { value: '3', label: '兼职博主' }
      ]
      platformTypeOptions.value = [
        { value: '1', label: '抖音' },
        { value: '2', label: '小红书' },
        { value: '3', label: '快手' },
        { value: '4', label: 'B站' }
      ]
    }
  } catch (error) {
    console.error('获取数据字典失败:', error)
    ElMessage.error('获取数据字典失败，使用默认数据')
    
    // 出错时使用默认数据
    professionTypeOptions.value = [
      { value: '1', label: '自媒体运营者' },
      { value: '2', label: '公司运营' },
      { value: '3', label: '兼职博主' }
    ]
    platformTypeOptions.value = [
      { value: '1', label: '抖音' },
      { value: '2', label: '小红书' },
      { value: '3', label: '快手' },
      { value: '4', label: 'B站' }
    ]
  }
}

// 获取用户信息
const getUser = async () => {
  try {
    const { data } = await getUserProfileApi()
    Object.assign(userInfo.value, data)
    Object.assign(userForm, {
      id: data.sysUser.id,
      nickname: data.sysUser.nickname,
      mobile: data.sysUser.mobile,
      email: data.sysUser.email,
      wechat: data.sysUser.wechat || '',
      sex: data.sysUser.sex,
      professionType: data.sysUser.professionType || '',
      platformTarget: data.sysUser.platformTarget || '',
      industryTagIds: data.sysUser.industryTagIds || [],
      socialMediaList: []
    })
    
    // 单独加载社交平台数据
    await loadSocialMediaList()
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 社交平台相关方法
const addSocialPlatform = async () => {
  const newPlatform = {
    platformType: '',
    homeUrl: '',
    fansCount: 0,
    verificationType: 0,
    isNew: true // 标记为新增
  }
  userForm.socialMediaList.push(newPlatform)
}

const removeSocialPlatform = async (index: number) => {
  const platform = userForm.socialMediaList[index]
  
  // 如果是已保存的数据，调用删除API
  if (platform.id && !platform.isNew) {
    try {
      await deleteUserSocialMediaApi(platform.id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      return
    }
  }
  
  // 从列表中移除
  userForm.socialMediaList.splice(index, 1)
}

// 保存单个社交平台
const saveSocialPlatform = async (platform: any, index: number) => {
  try {
    // 检查用户ID是否存在
    if (!userForm.id) {
      ElMessage.error('用户信息不完整，请刷新页面重试')
      return
    }
    
    // 验证必填字段
    if (!platform.platformType || !platform.homeUrl) {
      ElMessage.warning('请完善平台信息')
      return
    }
    
    const platformData = {
      userId: userForm.id,
      platformType: platform.platformType,
      homeUrl: platform.homeUrl,
      fansCount: platform.fansCount || 0,
      verificationType: platform.verificationType || 0
    }
    
    if (platform.isNew || !platform.id) {
      // 新增
      const { data } = await createUserSocialMediaApi(platformData)
      platform.id = data.id
      platform.isNew = false
      ElMessage.success('添加成功')
    } else {
      // 修改
      await updateUserSocialMediaApi({
        id: platform.id,
        ...platformData
      })
      ElMessage.success('修改成功')
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 批量保存社交平台
const batchSaveSocialPlatforms = async () => {
  try {
    if (!userForm.id) {
      ElMessage.error('用户信息不完整，请刷新页面重试')
      return
    }
    
    const socialMediaList = userForm.socialMediaList.map(item => ({
      id: item.id,
      platformType: item.platformType,
      homeUrl: item.homeUrl,
      fansCount: item.fansCount || 0,
      verificationType: item.verificationType || 0
    }))
    
    await batchSaveUserSocialMediaApi({
      userId: userForm.id,
      socialMediaList
    })
    
    ElMessage.success('保存成功')
    await loadSocialMediaList() // 重新加载数据
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 加载社交平台列表
const loadSocialMediaList = async () => {
  try {
    if (userForm.id) {
      const { data } = await getUserSocialMediaApi(userForm.id)
      userForm.socialMediaList = data || []
    }
  } catch (error) {
    console.error('加载社交平台数据失败:', error)
    userForm.socialMediaList = []
  }
}

// 提交用户表单
const submitUserForm = async () => {
  try {
    submitLoading.value = true
    await userFormRef.value.validate()
    
    // 创建提交数据，排除社交平台数据
    const submitData = {
      id: userForm.id,
      nickname: userForm.nickname,
      mobile: userForm.mobile,
      email: userForm.email,
      wechat: userForm.wechat,
      sex: userForm.sex,
      professionType: userForm.professionType,
      platformTarget: userForm.platformTarget,
      industryTagIds: userForm.industryTagIds
    }
    
    await updateUserProfileApi(submitData)
    ElMessage.success('修改成功')
    getUser()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 提交密码表单
const submitPwdForm = async () => {
  try {
    pwdLoading.value = true
    await pwdFormRef.value.validate()
    await updateUserPwdApi(pwdForm.oldPassword, pwdForm.newPassword)
    ElMessage.success('修改成功')
    Object.assign(pwdForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    pwdLoading.value = false
  }
}

const getPlatformName = (platformType: string | number) => {
  const platform = platformTypeOptions.value.find(item => item.value == platformType)
  return platform?.label || '未知平台'
}

const getPlatformTagType = (platformType: string | number) => {
  const typeMap: any = {
    '1': 'danger',    // 抖音
    '2': 'warning',   // 小红书
    '3': 'success',   // 快手
    '4': 'info'       // B站
  }
  return typeMap[platformType] || 'info'
}

onMounted(() => {
  getUser()
  getDictData()
})
</script>

<style lang="scss" scoped>
.profile-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.profile-header {
  position: relative;
  height: 200px;
  
  .header-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  }
  
  .header-content {
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: white;
    padding: 20px;
    
    .profile-avatar {
      border: 4px solid rgba(255, 255, 255, 0.8);
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
    }
    
    .profile-name {
      margin: 15px 0 10px;
      font-size: 24px;
      font-weight: 600;
    }
  }
}

.profile-info {
  padding: 20px;
  
  .profile-list {
    padding: 0;
    margin: 0;
    list-style: none;
    
    li {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .info-label {
        display: flex;
        align-items: center;
        color: #666;
        
        .el-icon {
          margin-right: 8px;
          font-size: 16px;
        }
      }
      
      .info-content {
        color: #333;
        font-weight: 500;
      }
    }
  }
}

.tab-card {
  border-radius: 8px;
  
  :deep(.el-tabs__nav-wrap) {
    padding: 0 20px;
  }
}

.profile-form {
  max-width: 900px;
  margin: 0 auto;
  padding: 30px 40px;
  
  // 表单项间距优化
  :deep(.el-form-item) {
    margin-bottom: 28px;
    
    // 标签样式
    .el-form-item__label {
      font-weight: 500;
      color: #333;
      line-height: 1.6;
    }
    
    // 输入框样式
    .el-input__wrapper {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.2s;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
    }
    
    // 选择器样式
    .el-select {
      .el-input__wrapper {
        &:hover {
          box-shadow: 0 0 0 1px #c0c4cc inset;
        }
      }
    }
  }
  
  // 性别单选框样式优化
  .gender-form-item {
    :deep(.el-radio-group) {
      .el-radio {
        margin-right: 24px;
        
        .el-radio__label {
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
  
  // 文本域样式优化
  .textarea-form-item {
    margin-bottom: 32px;
    
    :deep(.el-textarea) {
      .el-textarea__inner {
        resize: vertical;
        min-height: 100px;
        line-height: 1.6;
        font-family: inherit;
      }
    }
  }
  
  // 标签选择器样式优化
  .tags-form-item {
    margin-bottom: 36px;
    
    :deep(.el-form-item__content) {
      line-height: normal;
    }
  }
  
  // 提交按钮样式优化
  .submit-form-item {
    margin-bottom: 0;
    margin-top: 40px;
    text-align: center;
    padding-top: 24px;
    border-top: 1px solid #f0f0f0;
    
    .el-button {
      min-width: 140px;
      height: 44px;
      font-size: 16px;
      font-weight: 500;
      border-radius: 6px;
      
      .el-icon {
        margin-right: 6px;
      }
    }
  }
  
  // 响应式设计
  @media (max-width: 768px) {
    padding: 20px;
    max-width: 100%;
    
    :deep(.el-form-item) {
      margin-bottom: 20px;
    }
    
    .submit-form-item {
      margin-top: 30px;
      padding-top: 20px;
    }
  }
}

.profile-tabs {
  :deep(.el-tabs__item) {
    font-size: 15px;
    
    &.is-active {
      font-weight: 600;
    }
  }
}

/* 社交平台样式 */
.social-platform-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h3 {
      margin: 0;
      color: var(--el-text-color-primary);
      font-size: 18px;
      font-weight: 600;
    }
  }
  
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }
  
  .platform-list {
    display: grid;
    gap: 20px;
  }
  
  .platform-card {
    border-radius: 12px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    }
    
    .platform-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .platform-title {
        display: flex;
        align-items: center;
      }
      
      .platform-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    :deep(.el-card__body) {
      padding: 20px;
    }
  }
  
  .form-actions {
    margin-top: 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-light);
  }
}
</style>